package org.springcloud.plugin.framework.nacos.decorator;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.cloud.nacos.ribbon.NacosServerList;
import org.apache.commons.collections4.CollectionUtils;
import org.springcloud.plugin.framework.listener.loadbalance.LoadBalanceListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.List;

/**
 * @Author yanggld
 * @Date 2019/12/9-16:55
 * @Description
 * 服务列表实例
 */
public class NacosServerListDecorator extends NacosServerList {

	private ConfigurableEnvironment environment;

	private List<LoadBalanceListener> loadBalanceListeners;

	public NacosServerListDecorator(NacosDiscoveryProperties nacosDiscoveryProperties) {
		super(nacosDiscoveryProperties);
	}

	@Override
	public List<NacosServer> getInitialListOfServers() {
		List<NacosServer> servers = super.getInitialListOfServers();
		filter(servers);
		return servers;
	}

	/**
	 * 1. 第一次负载均衡出发
	 * 2. 以后30s定时触发
	 * @return
	 */
	@Override
	public List<NacosServer> getUpdatedListOfServers() {
		System.out.println(System.currentTimeMillis()+"---getUpdatedListOfServers");
		List<NacosServer> servers = super.getUpdatedListOfServers();
		filter(servers);
		return servers;
	}

	private void filter(List<NacosServer> servers) {
		Boolean discoveryControlEnabled = environment.getProperty("spring.application.discovery.control.enabled", Boolean.class,Boolean.TRUE);
		if (discoveryControlEnabled) {
			String serviceId = getServiceId();
			if (CollectionUtils.isNotEmpty(loadBalanceListeners)) {
				for (LoadBalanceListener loadBalanceListener : loadBalanceListeners) {
					loadBalanceListener.onGetServers(serviceId, servers);
				}
			}
		}
	}

	public void setEnvironment(ConfigurableEnvironment environment) {
		this.environment = environment;
	}

	public void setLoadBalanceListeners(List<LoadBalanceListener> loadBalanceListeners) {
		this.loadBalanceListeners = loadBalanceListeners;
	}
}
